<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

// +----------------------------------------------------------------------+
// | Treacle PHP Framework Version 0.10                                   |
// +----------------------------------------------------------------------+
// | Copyright (c) 2007 Treacle.cn All rights reserved.					  |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the 'License');      |
// | you may not use this file except in compliance with the License.     |
// | You may obtain a copy of the License at                              |
// | http://www.apache.org/licenses/LICENSE-2.0                           |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an 'AS IS' BASIS,    |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
// | implied. See the License for the specific language governing         |
// | permissions and limitations under the License.                       |
// +----------------------------------------------------------------------+
// | Author: BoPo <ibopo@126.com>										  |
// +----------------------------------------------------------------------+
/**
 * 数据库驱动类文件
 *
 * @author BoPo <ibopo@126.com>
 * @link http://www.treacle.cn/
 * @copyright Copyright &copy; 2007 Treacle
 * @license http://www.treacle.cn/license/
 * @version $Id $
 * @package database
 */
/**
 * 数据库驱动类
 *
 * @package	database
 * @author BoPo <ibopo@126.com>
 * @since 0.10
 * @version	$Id $
 */
abstract class DB_driver
{
	private $username;
	private $password;
	private $hostname;
	private $database;
	private $dbdriver		= 'mysql';
	private $dbprefix		= '';
	private $port			= '';
	private $pconnect		= false;
	private $conn_id		= false;
	private $result_id		= false;
	private $db_debug		= false;
	private $benchmark		= 0;
	private $query_count	= 0;
	private $bind_marker	= '?';
	private $queries		= array();
	private $trans_enabled	= true;
	private $_trans_depth	= 0;
	private $_trans_status	= true; // 事务状态
	private $stmt_id;
	private $curs_id;
	private $limit_used;
	/**
	 * 构造函数,初始化数据库设置
	 *
	 * $dsn = 'driver://username:password@hostname/database';
	 *
	 * @param mixed.
	 */
	public function __construct($params)
	{
		$this->initialize($params);
	}

	function __get($var)
	{
		if (isset($this->$var))	return $this->$var;
		return false;
	}
	/**
	 * 初始化数据库设置
	 *
	 * @access	private
	 * @param	mixed
	 * @return	void
	 */
	public function initialize($params = '')
	{
		if (is_array($params))
		{
			$defaults = array(
			'hostname'	=> '',
			'username'	=> '',
			'password'	=> '',
			'database'	=> '',
			'conn_id'	=> false,
			'dbdriver'	=> 'mysql',
			'dbprefix'	=> '',
			'port'		=> '',
			'pconnect'	=> false,
			'db_debug'	=> true,
			);
			foreach ($defaults as $key => $val)
			{
				$this->$key = ( ! isset($params[$key])) ? $val : $params[$key];
			}
		}
		elseif (strpos($params, '://'))
		{
			if (false === ($dsn = @parse_url($params)))
			{
				if (DEBUG)
				{
					throw new TDbException('db_invalid_connection_str');
				}
				return false;
			}
			$this->hostname = ( ! isset($dsn['host'])) ? '' : rawurldecode($dsn['host']);
			$this->username = ( ! isset($dsn['user'])) ? '' : rawurldecode($dsn['user']);
			$this->password = ( ! isset($dsn['pass'])) ? '' : rawurldecode($dsn['pass']);
			$this->database = ( ! isset($dsn['path'])) ? '' : rawurldecode(substr($dsn['path'], 1));
		}
		// If an existing DB connection resource is supplied
		// there is no need to connect and select the database
		if (is_resource($this->conn_id))
		{
			return true;
		}
		// Connect to the database
		$this->conn_id = ($this->pconnect == false) ? $this->db_connect() : $this->db_pconnect();
		// No connection?  Throw an error
		if ( ! $this->conn_id)
		{
			if (DEBUG)
			{
				throw new TDbException('db_unable_to_connect');
			}
			return false;
		}
		// Select the database
		if ($this->database != '')
		{
			if ( ! $this->db_select())
			{
				if (DEBUG)
				{
					throw new TDbException('db_unable_to_select');
				}
				return false;
			}
		}
		return true;
	}
	/**
	 * 获取平台名称(例如 mysql,mssql,sqlite等等)
	 *
	 * @access	public
	 * @return	string
	 */
	public function platform()
	{
		return $this->dbdriver;
	}
	/**
	 * 获取数据库版本号
	 *
	 * @access	public
	 * @return	string
	 */
	public function version()
	{
		if (false === ($sql = $this->_version()))
		{
			if (DEBUG)
			{
				throw new TDbException('db_unsupported_function');
			}
			return false;
		}
		if ($this->dbdriver == 'oci8')
		{
			return $sql;
		}
		$query	= $this->query($sql);
		$row	= $query->row();
		return $row->ver;
	}
	/**
	 * 执行查询操作
	 *
	 * @access	public
	 * @param	string	SQL query string
	 * @param	array
	 * @return	mixed
	 */
	public function query($sql, $binds = false, $return_object = true)
	{
		if ($sql == '')
		{
			if (DEBUG)
			{
				throw new TDbException('db_invalid_query');
			}
			return false;
		}
		// Compile binds if needed
		if ($binds !== false)
		{
			$sql = $this->compile_binds($sql, $binds);
		}
		// Save the  query for debugging
		$this->queries[] = $sql;
		// Start the Query Timer
		$time_start = list($sm, $ss) = explode(' ', microtime());
		// Run the Query
		if (false === ($this->result_id = $this->simple_query($sql)))
		{
			// This will trigger a rollback if transactions are being used
			$this->_trans_status = false;
			if (DEBUG)
			{
				throw new TDbException($this->_error_message(),$this->_error_number(),$sql);
			}
			return false;
		}
		// Stop and aggregate the query time results
		$time_end = list($em, $es) = explode(' ', microtime());
		$this->benchmark += ($em + $es) - ($sm + $ss);
		// Increment the query counter
		$this->query_count++;
		// Was the query a "write" type?
		// If so we'll simply return true
		if ($this->_is_write_type($sql) === true)
		{
			return true;
		}
		// Return true if we don't need to create a result object
		// Currently only the Oracle driver uses this when stored
		// procedures are used
		if ($return_object !== true)
		{
			return true;
		}
		// Load and instantiate the result driver
		$driver 		= $this->load_rdriver();
		$RES 			= new $driver();
		$RES->conn_id	= $this->conn_id;
		$RES->result_id	= $this->result_id;
		if ($this->dbdriver == 'oci8')
		{
			$RES->stmt_id		= $this->stmt_id;
			$RES->curs_id		= NULL;
			$RES->limit_used	= $this->limit_used;
		}
		return $RES;
	}
	/**
	 * 加载结果类驱动文件
	 *
	 * @access	public
	 * @return	string 	result class
	 */
	public function load_rdriver()
	{
		$driver = 'DB_'.$this->dbdriver.'_result';
		if ( ! class_exists($driver))
		{
			include_once(BASEPATH.'database/DB_result'.EXT);
			include_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result'.EXT);
		}
		return $driver;
	}
	/**
	 * 执行一个简单查询
	 *
	 * @access	public
	 * @param	string	sql query
	 * @return	mixed
	 */
	public function simple_query($sql)
	{
		if (!$this->conn_id)
		{
			$this->initialize();
		}
		return $this->_execute($sql);
	}
	/**
	 * 关闭事务功能
	 *
	 * @access	public
	 * @return	void
	 */
	public function trans_off()
	{
		$this->trans_enabled = false;
	}
	/**
	 * 事务开始方法
	 *
	 * @access	public
	 * @return	void
	 */
	public function trans_start($test_mode = false)
	{
		if (!$this->trans_enabled)
		{
			return false;
		}
		// When transactions are nested we only begin/commit/rollback the outermost ones
		if ($this->_trans_depth > 0)
		{
			$this->_trans_depth += 1;
			return;
		}
		$this->trans_begin($test_mode);
	}
	/**
	 * 完成事务
	 *
	 * @access	public
	 * @return	bool
	 */
	public function trans_complete()
	{
		if ( ! $this->trans_enabled)
		{
			return false;
		}
		// When transactions are nested we only begin/commit/rollback the outermost ones
		if ($this->_trans_depth > 1)
		{
			$this->_trans_depth -= 1;
			return true;
		}
		// The query() function will set this flag to true in the event that a query failed
		if ($this->_trans_status === false)
		{
			$this->trans_rollback();

			if (DEBUG)
			{
				throw new TDbException('db_transaction_failure');
			}
			return false;
		}
		$this->trans_commit();
		return true;
	}
	/**
	 * 获取事务状态
	 *
	 * @access	public
	 * @return	bool
	 */
	public function trans_status()
	{
		return $this->_trans_status;
	}
	/**
	 * 编译组装
	 *
	 * @access	public
	 * @param	string	the sql statement
	 * @param	array	an array of bind data
	 * @return	string
	 */
	private function compile_binds($sql, $binds)
	{
		if (false === strpos($sql, $this->bind_marker))
		{
			return $sql;
		}
		if ( ! is_array($binds))
		{
			$binds = array($binds);
		}
		foreach ($binds as $val)
		{
			$val = $this->escape($val);
			// Just in case the replacement string contains the bind
			// character we'll temporarily replace it with a marker
			$val = str_replace($this->bind_marker, '{%bind_marker%}', $val);
			$sql = preg_replace("#".preg_quote($this->bind_marker, '#')."#", str_replace('$', '\$', $val), $sql, 1);
		}
		return str_replace('{%bind_marker%}', $this->bind_marker, $sql);
	}
	/**
	 * 判断是否是对数据库进行写操作
	 *
	 * @access	public
	 * @param	string	SQL 查询字符串
	 * @return	boolean
	 */
	private function _is_write_type($sql)
	{
		if ( ! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|LOAD DATA|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s+/i', $sql))
		{
			return false;
		}
		return true;
	}
	/**
	 * 获取查询所花费的时间
	 *
	 * @access	public
	 * @param	integer	格式化显示的小数点位数
	 * @return	integer
	 */
	public function elapsed_time($decimals = 6)
	{
		return number_format($this->benchmark, $decimals);
	}
	/**
	 * 返回查询数据库的次数
	 *
	 * @access	public
	 * @return	integer
	 */
	public function total_queries()
	{
		return $this->query_count;
	}
	/**
	 * 返回最后执行的内容
	 *
	 * @access	public
	 * @return	void
	 */
	public function last_query()
	{
		return end($this->queries);
	}
	/**
	 * 自动判断数据类型
	 *
	 * Escapes data based on type
	 * Sets boolean and null types
	 *
	 * @access	public
	 * @param	string
	 * @return	integer
	 */
	public function escape($str)
	{
		switch (gettype($str))
		{
			case 'string'	:	$str = "'".$this->escape_str($str)."'";
			break;
			case 'boolean'	:	$str = ($str === false) ? 0 : 1;
			break;
			default			:	$str = ($str === NULL) ? 'NULL' : $str;
			break;
		}
		return $str;
	}
	/**
	 * 主键
	 *
	 * Retrieves the primary key.  It assumes that the row in the first
	 * position is the primary key
	 *
	 * @access	public
	 * @param	string	the table name
	 * @return	string
	 */
	public function primary($table = '')
	{
		$fields = $this->list_fields($table);
		if ( ! is_array($fields))
		{
			return false;
		}
		return current($fields);
	}
	/**
	 * 以数组形式返回所有的表名
	 *
	 * @access	public
	 * @return	array
	 */
	public function list_tables()
	{
		if (false === ($sql = $this->_list_tables()))
		{
			if (DEBUG)
			{
				throw new TDbException('db_unsupported_function');
			}
			return false;
		}
		$retval = array();
		$query = $this->query($sql);
		if ($query->num_rows() > 0)
		{
			foreach($query->result_array() as $row)
			{
				if (isset($row['TABLE_NAME']))
				{
					$retval[] = $row['TABLE_NAME'];
				}
				else
				{
					$retval[] = array_shift($row);
				}
			}
		}
		return $retval;
	}
	/**
	 * 判断表是否存在
	 * @access	public
	 * @return	boolean
	 */
	public function table_exists($table_name)
	{
		return ( ! in_array($this->dbprefix.$table_name, $this->list_tables())) ? false : true;
	}
	/**
	 * 获取数据库的字段名
	 * @access	public
	 * @param	string	the table name
	 * @return	array
	 */
	public function list_fields($table = '')
	{
		// Is there a cached result?
		if ($table == '')
		{
			if (DEBUG)
			{
				throw new TDbException('db_field_param_missing');
			}
			return false;
		}
		if (false === ($sql = $this->_list_columns($this->dbprefix.$table)))
		{
			if (DEBUG)
			{
				throw new TDbException('db_unsupported_function');
			}
			return false;
		}
		$query	= $this->query($sql);
		$retval = array();
		foreach($query->result_array() as $row)
		{
			if (isset($row['COLUMN_NAME']))
			{
				$retval[] = $row['COLUMN_NAME'];
			}
			else
			{
				$retval[] = current($row);
			}
		}
		return $retval;
	}

	/**
	 * 判断字段是否存在
	 * @access	public
	 * @param	string
	 * @param	string
	 * @return	boolean
	 */
	public function field_exists($field_name, $table_name)
	{
		return ( ! in_array($field_name, $this->list_fields($table_name))) ? false : true;
	}

	/**
	 * list_fields()的别名
	 */
	public function field_names($table = '')
	{
		return $this->list_fields($table);
	}

	/**
	 * Returns an object with field data
	 *
	 * @access	public
	 * @param	string	the table name
	 * @return	object
	 */
	public function field_data($table = '')
	{
		if ($table == '')
		{
			if (DEBUG)
			{
				throw new TDbException('db_field_param_missing');
			}
			return false;
		}
		$query = $this->query($this->_field_data($this->dbprefix.$table));
		return $query->field_data();
	}

	/**
	 * 构造一个insert查询的字符串
	 *
	 * @access	public
	 * @param	string	the table upon which the query will be performed
	 * @param	array	an associative array data of key/values
	 * @return	string
	 */
	public function insert_string($table, $data)
	{
		$fields = array();
		$values = array();
		foreach($data as $key => $val)
		{
			$fields[] = $key;
			$values[] = $this->escape($val);
		}
		return $this->_insert($this->dbprefix.$table, $fields, $values);
	}

	/**
	 * 构造一个update查询的字符串
	 *
	 * @access	public
	 * @param	string	the table upon which the query will be performed
	 * @param	array	an associative array data of key/values
	 * @param	mixed	the "where" statement
	 * @return	string
	 */
	public function update_string($table, $data, $where)
	{
		if ($where == '')
		{
			return false;
		}
		$fields = array();
		foreach($data as $key => $val)
		{
			$fields[$key] = $this->escape($val);
		}
		if ( ! is_array($where))
		{
			$dest = array($where);
		}
		else
		{
			$dest = array();
			foreach ($where as $key => $val)
			{
				$prefix = (count($dest) == 0) ? '' : ' AND ';
				if ($val != '')
				{
					if ( ! $this->_has_operator($key))
					{
						$key .= ' =';
					}

					$val = ' '.$this->escape($val);
				}
				$dest[] = $prefix.$key.$val;
			}
		}
		return $this->_update($this->dbprefix.$table, $fields, $dest);
	}
	/**
	 * 调用针对于正使用的数据库类型的PHP函数
	 *
	 * @access	public
	 * @param	string	the function name
	 * @param	mixed	any parameters needed by the function
	 * @return	mixed
	 */
	public function call_function($function)
	{
		$driver = ($this->dbdriver == 'postgre') ? 'pg_' : $this->dbdriver.'_';
		if (false === strpos($driver, $function))
		{
			$function = $driver.$function;
		}
		if ( ! function_exists($function))
		{
			if (DEBUG)
			{
				throw new TDbException('db_unsupported_function');
			}
			return false;
		}
		else
		{
			$args = (func_num_args() > 1) ? array_splice(func_get_args(), 1) : null;
			return call_user_func_array($function, $args);
		}
	}
	/**
	 * 关闭数据库链接
	 *
	 * @access	public
	 * @return	void
	 */
	public function close()
	{
		if (is_resource($this->conn_id))
		{
			$this->_close($this->conn_id);
		}
		$this->conn_id = false;
	}
}
/*
+---------------------------------------------------------------------------
|   Last Modified By BoPo
|   Date: Wed Sep 05 17:24:34 CST 2007
+--------------------------------------------------------------------------
*/
?>